﻿using System;
using System.Collections.Generic;
using System.Threading;
using Lidgren.Network;
using NetBrick.Server;
using UniBrickCommon;
using UniBrickCommon.Packets;
using UniBrickServer.Utils;
using UnityEngine;

namespace UniBrickServer
{
    public class UniBrickPeer : BasePeer
    {
        //private readonly Thread _updateThread;

        public UniBrickPeer(NetConnection connection)
            : base(connection)
        {
            Authenticated = false;
            //_updateThread = new Thread(() =>
            //{
            //    while (Authenticated && !Environment.HasShutdownStarted)
            //    {
            //        var updatePacket = new UpdatePacket.Event(Name, Position.ToVectorString(), Rotation.ToQuaternionString());
            //        UniBrickServer.Instance.BroadcastPacketToAuthenticated(UniBrickPacketCode.UpdateEvent, updatePacket,
            //            NetDeliveryMethod.ReliableOrdered);
            //        Thread.Sleep(25);
            //    }
            //});
        }

        public Dictionary<byte, object> PlayerData { get; private set; }
        public bool Authenticated { get; private set; }
        public string Name { get; private set; }

        public Vector3 Position
        {
            get { return ((string) PlayerData[ServerConstants.UserdataPosition]).ToVector(); }
            set { PlayerData[ServerConstants.UserdataPosition] = value.ToVectorString(); }
        }

        public Quaternion Rotation
        {
            get { return ((string) PlayerData[ServerConstants.UserdataRotation]).ToQuaternion(); }
            set { PlayerData[ServerConstants.UserdataRotation] = value.ToQuaternionString(); }
        }

        public string World
        {
            get { return (string) PlayerData[ServerConstants.UserdataWorld]; }
            set { PlayerData[ServerConstants.UserdataWorld] = value; }
        }

        public string[] Friends
        {
            get { return (string[]) PlayerData[ServerConstants.UserdataFriendList]; }
            set { PlayerData[ServerConstants.UserdataFriendList] = value; }
        }

        public void Authenticate(string name)
        {
            if (Authenticated) return;
            Name = name;
            Authenticated = true;
            PlayerData = PlayerUtils.LoadPlayerData(name);
            //_updateThread.Start();
        }

        public override void OnConnect()
        {
            Log.Info("An unauthenticated user connected.");
        }

        public override void OnDisconnect(string reason)
        {
            Log.Info((Authenticated ? "User " + Name : "An unauthenticated user") + " disconnected for reason {0}",
                reason);

            if(Authenticated)
            {
                UniBrickServer.Instance.Players.Remove(Name);
            }

            Authenticated = false;
        }
    }
}